package com.college.common.utils.sign;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSON;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 小C工作室
 * @date 2022/12/20 14:33
 * @project manager_system_server_axh
 * @company 韦伯创想
 * @description
 */
public class MapUtils {

    public static <T> String convertMap2String(Map<String, T> paramsMap) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<>(paramsMap.keySet());
        Collections.sort(keys);
        int index = 0;
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            Object value = paramsMap.get(key);
            if (!key.isEmpty() && value != null) {
                content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                index++;
            }
        }
        return content.toString();
    }

    /**
     * 将String转Map
     */
    public static Map<String, String> convertString2Map(String targetString) {
        Map<String, String> map = new HashMap<>();
        String[] strings = targetString.split("&");
        for (int i = 0; i < strings.length; i++) {
            String[] keyValue = strings[i].split("=");
            map.put(keyValue[0], keyValue[1]);
        }
        return map;
    }

    public static String getSign(Map<String, Object> postParameters, String connector, String spacer) {
        System.out.println("加签前：" + postParameters);
        Set<String> keySet = postParameters.keySet();
        return keySet.stream().sorted(Comparator.naturalOrder()).map(s -> s + connector + postParameters.get(s)).collect(Collectors.joining(spacer));
    }

    public static String getSign(String parameString, String keyTitle, String key) {
        Map<String, Object> req = JSON.parseObject(parameString, Map.class);
        String signStr = MapUtils.getSign(req, "=", "&") + "&" + keyTitle + "=" + key;

        String md5 = DigestUtil.md5Hex(signStr);

        System.out.println("signStr = " + signStr);
        System.out.println("DigestUtil.md5Hex(signStr) = " + md5);
        return md5;
    }

    public static boolean isNotBlank(Map map) {
        return map != null && !map.isEmpty();
    }

    public static void main(String[] args) {
        String text = "{\n" +
                "\t\"sellDate\": \"20240129\",\n" +
                "\t\"flightLineId\": \"56D69CE184E544DA94ED1EA7305833AB\",\n" +
                "\t\"isInterest\": \"\",\n" +
                "\t\"feature\": \"\",\n" +
                "\t\"appKey\": \"WX-YZ9mPxzxdn\",\n" +
                "\t\"flightStr\": \"\",\n" +
                "\t\"hotelGly\": \"\"\n" +
                "}";

        System.out.println(getSign(text, "appSecret", "DflutfE0dnIzd9pO"));
    }
}
